package com.wy.leetCode;

/**
 * @author HelloWorld
 * @create 2021/9/23 8:57
 * @email 154803771@qq.com
 */
public class SwitchString {
    public static void main(String[] args) {
        SwitchString switchString = new SwitchString();
        System.out.println(switchString.myAtoi("9223372036854775808"));
    }

    int myAtoi(String s) {

        // 1.去字符串前面的空格
        s = s.trim();

        // 2.遍历字符串 "9223372036854775808"
        char[] charArray = s.toCharArray();

        if (charArray.length == 0){
            return 0;
        }

        long result = 0;
        boolean minus = false;
        if (charArray[0] == '-') {
            minus = true;
        }
        // 【当数字超过Long范围的时候会有转换异常，所以当数字大小超过int的时候就进行输出】
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i];
            if (c <= '9' && c >= '0'){
                result = result * 10 + c - '0';

                if(result >= 2147483647){
                    if (!minus){
                        return 2147483647;
                    }else if (result >= 2147483648L) {
                        return -2147483648;
                    }
                }
            } else if (i == 0 && (c == '+' || c == '-')){
                continue;
            } else {
                break;
            }
        }

        if (minus) {
            result *= -1;
        }
        return (int) result;
    }
}
